package com.euc.springbootframework.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.lang.reflect.ParameterizedType;
import java.util.List;

public abstract class BaseMongoDbDao<T>  {
    private static final int DEFAULT_SKIP = 0;
    private static final int DEFAULT_LIMIT = 200;

    public Class<?> getEntityClass(){
        return (Class<?>)((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    @Autowired
    protected MongoTemplate mongoTemplate;

    public List<T> find(Query query) {
        return this.mongoTemplate.find(query, (Class<T>) this.getEntityClass());
    }

    public T findOne(Query query) {
        return mongoTemplate.findOne(query, (Class<T>) this.getEntityClass());
    }

    public void update(Query query, Update update) {
        mongoTemplate.findAndModify(query, update, this.getEntityClass());
    }

    public T save(T entity) {
        mongoTemplate.insert(entity);
        return entity;
    }

    public T findById(String id) {
        return mongoTemplate.findById(id, (Class<T>) this.getEntityClass());
    }

    public T findById(String id, String collectionName) {
        return mongoTemplate.findById(id, (Class<T>) this.getEntityClass(), collectionName);
    }


    public long count(Query query){
        return mongoTemplate.count(query, this.getEntityClass());
    }
}
